<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /*
            定义一个sendAjax()函数，对于xhr的get请求进行封装:
                1.该函数接收两个参数: url(请求地址)、data(请求参数)
                2.该函数返回一个promise实例
                    (1). 若ajax请求成功，则promise实例成功，成功的value是返回的数据
                    (2). 若ajax请求失败，则promise实例失败，失败的reason是错误提示
        */
        function sendAjax(url, data) {
            return new Promise((resolve, reject) => {
                let xhr = new XMLHttpRequest()
                xhr.onreadystatechange = () => {
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200) {
                            resolve(xhr.response)
                        } else {
                            reject('请求失败，出了点小差错')
                        }
                    }
                }
                let str = ''
                for (let key in data) {
                    str += `${key}=${data[key]}&`
                }
                str = str.slice(0, -1)
                xhr.oepn('GET', url + '?' + str)
                xhr.send()
            })
        }
    </script>
</body>

</html>